<template>
  <div class='container'>
      <el-header><span>{{$route.query.isEdit==='1'?'修改试题':'试题录入'}}</span></el-header>
      <el-main>
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
          <el-form-item label="学科:" prop="subjectID" >
            <el-select @change="subchange" v-model="form.subjectID" placeholder="请选择" class="select-width">
              <el-option v-for="item in subList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID" >
            <el-select v-model="form.catalogID" placeholder="请选择" class="select-width" >
              <el-option v-for="item in dirList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID" >
            <el-select v-model="form.enterpriseID" placeholder="请选择" class="select-width">
              <el-option v-for="item in companysList " :key="item.id" :label="item.company" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="city" >
            <el-select @change="provinceChange" v-model="form.province" placeholder="请选择" style="width:195px;margin-right:10px">
              <el-option v-for="(item,index) in provinceList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <el-select v-model="form.city" placeholder="请选择" style="width:195px">
              <el-option v-for="(item,index) in cityList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select v-model="form.direction" placeholder="请选择" class="select-width">
              <el-option v-for="(item,index) in directionList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="form.questionType">
              <el-radio v-for="item in questionTypeList" :key="item.value" :label="item.value+=''">
                {{item.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio v-for="item in difficultyList" :key="item.value" :label="item.value+=''">
                {{item.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item ref="quill" label="题干:" prop="question">
            <quill-editor :options="editorOption" ref="myQuillEditor" @blur="quillfocus" v-model="form.question"></quill-editor>
          </el-form-item>

          <el-form-item label="选项:" v-if="form.questionType!=='3'">
            <template>
              <div v-for="(item,index) in form.options" :key="index" class="options">
                <el-radio v-if="form.questionType==='1'" v-model="isRight" :label="index">{{item.code+'：'}}</el-radio>
                <el-checkbox v-else v-model="item.isRight">{{item.code+'：'}}</el-checkbox>
                <el-input v-model="item.title" style="width:240px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :http-request="uploadImg"
                  @click.native="upimgrow(item)">
                  <img v-if="item.img" :src="item.img" class="avatar">
                  <span v-else>上传图片</span>
                  <i class="el-icon-circle-close"></i>
                </el-upload>
              </div>
            </template>
            <el-button @click="addoption" type="danger" size="mini" :disabled="form.questionType!=='2'">+增加选项与答案</el-button>
          </el-form-item>

          <el-form-item label="解析视频：">
            <el-input v-model="form.videoURL" class="select-width"></el-input>
          </el-form-item>
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor :options="editorOption" ref="myQuillEditor2" @blur="quillfocus2" v-model="form.answer"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注：">
            <el-input
              type="textarea"
              :rows="4"
              class="select-width"
              v-model="form.remarks">
            </el-input>
          </el-form-item>
          <el-form-item label="试题标签：">
            <el-select multiple  filterable allow-create v-model="form.tags" placeholder="请选择">
            <el-option
              v-for="item in tagsList" :key="item.id" :label="item.tagName" :value="item.tagName">
            </el-option>
          </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="$route.query.isEdit==='1'" type="success" @click="amendBtn">确认修改</el-button>
            <el-button v-else type="primary" @click="submit">确认提交</el-button>
          </el-form-item>
        </el-form>
  </el-main>
  </div>
</template>

<script>
import { simple as subsimple } from '../../api/hmmm/subjects'
import { simple as dirsimple } from '../../api/hmmm/directorys'
import { list as getcomList } from '../../api/hmmm/companys'
import { list as getTagsList } from '../../api/hmmm/tags'
import { add as addquestion, update, detail } from '../../api/hmmm/questions'
import { provinces, citys } from '../../api/hmmm/citys'
import { direction, difficulty, questionType } from '../../api/hmmm/constants'
import COS from 'cos-js-sdk-v5'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
hljs.configure({ // optionally configure hljs
  languages: ['javascript', 'ruby', 'python', 'html']
})
export default {
  data () {
    return {
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标题
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市', trigger: 'change' }],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入解析', trigger: 'blur' }]
      },
      subList: [],
      dirList: [],
      companysList: [],
      provinceList: provinces(),
      cityList: [],
      directionList: direction,
      difficultyList: difficulty,
      questionTypeList: questionType,
      isRight: '',
      tagsList: [],
      imgrow: {},
      // 富文本编辑器配置项
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        },
        theme: 'snow'
      }

    }
  },
  created () {
    this.getSubList()
    this.getCompanysList()
    // 路由跳转的函数
    this.routerPath()
  },
  watch: { // 监听
    $route (to, from) { // 路由变化方式，路由发生变化，方法就会执行
      this.form = {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标题
      }
      this.$refs.form.resetFields()
    }
  },
  methods: {
    // 获取学科列表
    async getSubList () {
      const res = await subsimple()
      // 翻转数组赋值
      this.subList = res.data.reverse()
    },
    // 根据学科获取目录列表
    async subchange (value) {
      // 学科发生变化重置目录内容
      this.form.catalogID = ''
      const res = await dirsimple({ subjectID: value })
      this.dirList = res.data.reverse()
      // 根据学科获取标签列表
      const res1 = await getTagsList({ subjectID: value })
      // console.log(res1.data.items)
      this.tagsList = res1.data.items
    },
    // 获取企业列表
    async getCompanysList () {
      const res = await getcomList()
      this.companysList = res.data.items.reverse()
    },
    // 根据城市获取县
    provinceChange (value) {
      this.form.city = ''
      this.cityList = citys(value)
    },
    // 题干失去焦点后自定义校验
    quillfocus () {
      this.$refs.form.validateField('question')
    },
    // 解析失去焦点后自定义校验
    quillfocus2 () {
      this.$refs.form.validateField('answer')
    },
    // 添加选项
    addoption () {
      // 获取最后一个选项的ascii码
      const index = this.form.options.length - 1
      const ascii = this.form.options[index].code.charCodeAt()
      this.form.options.push({ isRight: false, code: String.fromCharCode(ascii + 1), title: '', img: '' })
    },
    // 提交
    submit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log(1)
        // 数组转换成字符串格式
        this.form.tags += ''
        // 单选状态转换
        if (this.form.questionType === '1') {
          this.form.options[this.isRight].isRight = true
        }
        const res = await addquestion(this.form)
        if (res.status !== 200) return this.$message.error('试题录入失败')
        this.$message.success('试题录入成功!')
        this.$router.push('/questions/list')
      })
    },
    // 图片上传
    uploadImg ({ file }) {
      // console.log(file)
      var cos = new COS({
        SecretId: 'AKIDfBRRAdplPmsiJdgTyC9qGQJvGL9gU1GE',
        SecretKey: 'pOffOq1uWsxlJbdNq2ycz5uSjiQs2vXs'
      })
      cos.putObject({
        Bucket: 'x-1310934946', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file // 上传文件对象
        // onProgress: function (progressData) {
        //   console.log(JSON.stringify(progressData))
        // }
      }, (err, data) => {
        // console.log(err || data)
        if (data) {
          this.imgrow.img = 'http://' + data.Location
        } else {
          console.log(err)
        }
      })
    },
    // 获取上传图片的当前项
    upimgrow (row) {
      this.imgrow = row
      // console.log(row)
    },
    // 点击修改
    async amendBtn () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log(this.form)
        const res = await update(this.form)
        // console.log(res)
        if (res.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功!')
        this.$router.push('list')
      })
    },
    // 路由跳转
    async  routerPath () {
      if (this.$route.query.id) {
        const res = await detail({ id: this.$route.query.id })
        this.form = res.data
        // 单选框选择状态判断
        if (this.form.questionType === '1') {
          this.form.options.forEach((item, index) => {
            if (item.isRight === 1) {
              this.isRight = index
            }
          })
        }
        if (!this.form.options) {
          this.form.options = [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }]
        }
      } else {
        this.form = {
          subjectID: '', // 学科
          catalogID: '', // 目录
          enterpriseID: '', // 企业
          province: '', // 城市
          city: '', // 地区
          direction: '', // 方向
          questionType: '1', // 题型
          difficulty: '1', // 难度
          question: '', // 题干
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }], // 选项
          videoURL: '', // 解析视频
          answer: '', // 答案解析
          remarks: '', // 题目备注
          tags: [] // 试题标题
        }
      }
      // 跳转过来后滚动条在最上方
      // 等dom元素加载完毕在设置滚动条高度
      await this.$nextTick()
      document.documentElement.scrollTop = 0
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  margin: 20px;
  background-color: #fff;
  .el-header {
      padding: 0;
      display: flex;
      align-items: center;
      border-bottom:1px solid #ebeef5 ;
      span {
        margin-left: 20px;
      }
    }
  .select-width {
    width:400px
  }
  ::v-deep .ql-container {
    .ql-editor {
      height: 200px;
    }
    pre, code {
    font-size: 14px;
    font-family: Consolas;
    }
  }
  .options {
    margin-top: 10px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    .el-radio {
    margin:0;
  }
  ::v-deep.avatar-uploader{
    position: relative;
    width: 100px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px dashed  #ccc;
    margin-left: 5px;
    .el-upload.el-upload--text {
      width: 100%;
      height: 100%;
      .avatar {
        width: 100%;
        height: 100%;
      }
    }
    i {
      position: absolute;
      color: #aaa;
      right: -10px;
      top: -10px;
      z-index: 1;
      font-size: 18px;
    }
  }
  }

}
</style>
